package com.sjt.blog.web.admin;

import com.alibaba.fastjson.JSONObject;
import com.sjt.blog.po.Blog;
import com.sjt.blog.po.User;
import com.sjt.blog.service.BlogService;
import com.sjt.blog.service.OssService;
import com.sjt.blog.service.TagService;
import com.sjt.blog.service.TypeService;
import com.sjt.blog.vo.BlogQuery;
import com.sjt.blog.vo.OssCallbackResult;
import com.sjt.blog.vo.OssPolicyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/admin")
public class BlogController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private OssService ossService;

    @GetMapping("/blogs")
    public String list(@PageableDefault(size = 10,
            sort = {"updateTime"},
            direction = Sort.Direction.DESC) Pageable pageable,
                       BlogQuery blogQuery, Model model){
        model.addAttribute("types", typeService.listType());
        // blogQuery为封装的类，其拥有title、typeId、recommend三个属性
        model.addAttribute("page", blogService.listBlog(pageable, blogQuery));
        return "admin/blogs";
    }

    @PostMapping("/blogs/search")
    public String search(@PageableDefault(size = 10,
            sort = {"updateTime"},
            direction = Sort.Direction.DESC) Pageable pageable,
                       BlogQuery blogQuery, Model model){
        model.addAttribute("page", blogService.listBlog(pageable, blogQuery));
        return "admin/blogs :: blogList";
    }

    @GetMapping("/blogs/input")
    public String input(Model model){
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTags());
        model.addAttribute("blog", new Blog());
        return "admin/blogs-input";
    }

    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable("id") Long id, Model model){
        Blog blog = blogService.getBlog(id);
        blog.init();
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTags());
        model.addAttribute("blog", blog);
        return "admin/blogs-input";
    }


    @PostMapping("/blogs")
    public String doinput(Blog blog, RedirectAttributes attributes, HttpSession session){
        blog.setUser((User) session.getAttribute("user"));
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagService.listTags(blog.getTagIds()));

        Blog b;
        if (blog.getId() == null){
            b = blogService.saveBlog(blog);
        }else {
            b = blogService.updateBlog(blog.getId(), blog);
        }

        if (b == null){
            attributes.addFlashAttribute("message", "操作失败！");
        }else {
            attributes.addFlashAttribute("message", "操作成功！");
        }

        return "redirect:/admin/blogs";
    }


    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable("id") Long id, RedirectAttributes attributes){
        blogService.deleteBlog(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/blogs";
    }

    @GetMapping("/oss/policy")
    public String policy() {
        OssPolicyResult result = ossService.policy();
        return "";
    }

    @PostMapping("/oss/callback")
    public String callback(HttpServletRequest request) {
        OssCallbackResult ossCallbackResult = ossService.callback(request);
        return "";
    }


    // editor.md中编辑器的图片上传参数名为 editormd-image-file ，所以这里必须这样写
    // 而且 返回的需要视一个 json 对象，包含 success、message、url，所以这里必须要 @ResponseBody
    @PostMapping("/oss/upload")
    @ResponseBody
    public JSONObject upload(@RequestParam("editormd-image-file") MultipartFile file, Model model){
        JSONObject jsonObject = new JSONObject(); // 创建返回对象
        // 调用图片上传服务
        String url = ossService.upload(file);

        // 判断是否上传成功， 成功设置成功参数，否则设置为失败参数
        if (null == url){
            jsonObject.put("success", 0);
            jsonObject.put("message", "上传失败！");
        }else{
            jsonObject.put("success", 1);
            jsonObject.put("message", "上传成功！");
            jsonObject.put("url", url);
        }

        return jsonObject;
    }

}
